package com.pet.common.advice;

import cn.hutool.core.util.StrUtil;
import com.pet.common.domain.Result;
import com.pet.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class CommonExceptionAdvice {
    @ExceptionHandler(CommonException.class)
    public Result handleBadRequestException(CommonException e) {
        log.error("自定义异常 -> {} , 异常原因：{}  ", e.getClass().getName(), e.getMessage());
        log.debug("", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result doBusinessException(MethodArgumentNotValidException e) {
        StringBuilder errMsg = new StringBuilder();
        BindingResult bindResult = e.getBindingResult();
        List<FieldError> fieldErrorList = bindResult.getFieldErrors();
        fieldErrorList.forEach(fieldErrors -> {
            FieldError fieldError = fieldErrors;
            if (StrUtil.isNotBlank(errMsg.toString())) {
                errMsg.append(",");
            }
            errMsg.append(fieldError.getDefaultMessage());
        });
        errMsg.append("不能为空!");
        return Result.error(errMsg.toString());
    }
}
